import apiClient from '@/api/axios.js';

export class TravelNoteApi {
    // 1. 上传图片到阿里云
    static async uploadImage(file) {
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await apiClient.post('/travel-note/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
            return response.data; // 返回上传结果
        } catch (error) {
            throw new Error(error.message || '图片上传失败');
        }
    }

    // 2. 识别图片（动物或植物）
    static async detectImage(url, type) {
        try {
            const response = await apiClient.post(
                '/travel-note/detect',
                { url, type },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }
            );
            return response.data; // 返回识别结果
        } catch (error) {
            throw new Error(error.message || '图片识别失败');
        }
    }

    // 3. 获取关键词
    static async getKeywords(title, content) {
        try {
            const response = await apiClient.post(
                '/travel-note/getkeyword',
                { title, content },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }
            );
            return response.data; // 返回关键词列表
        } catch (error) {
            throw new Error(error.message || '获取关键词失败');
        }
    }

    // 获取收藏ID
    static async getFavoriteId(userID, articleID) {
        try {
            const response = await apiClient.get(
                `/travel-note/getByIds?userID=${userID}&articleID=${articleID}`,
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }
            );
            return response.data; // 返回收藏ID信息
        } catch (error) {
            // 如果是"收藏记录不存在"的错误，返回null而不是抛出异常
            if (error.response && error.response.data && error.response.data.includes("收藏记录不存在")) {
                return { status: "error", message: "收藏记录不存在" };
            }
            throw new Error(error.message || '获取收藏ID失败');
        }
    }

    // 4. 发布游记
    static async publishTravelNote(params) {
        const {
            authorID,
            title,
            content,
            favoriteCount = 0,// 不需要这个参数
            commentCount = 0,// 不需要这个参数
            creationTime = null,// 不需要这个参数
            recommendationIndex = 0,// 不需要这个参数
            latitude = 39.9042,
            longitude = 116.4074,
            status,
            img_url,
        } = params;
        const newParams = {
            article:{
                authorID,
                title,
                content,
                favoriteCount,
                commentCount,
                creationTime,
                recommendationIndex,
                latitude,
                longitude,
                status
            },
            img_url
        }
        console.log("newParams",newParams)
        try {
            const response = await apiClient.post(
                `/travel-note/publish`,
                newParams,
                {
                    // headers: {
                    //     'Content-Type': 'application/json',
                    // },
                }
            );
            return response.data; // 返回发布结果
        } catch (error) {
            throw new Error(error.message || '游记发布失败');
        }
    }

    // 5. 浏览游记
    static async browseTravelNote(articleID) {
        try {
            const response = await apiClient.get(`/travel-note/browse?articleID=${articleID}`, {
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            return response.data; // 返回游记详情
        } catch (error) {
            throw new Error(error.message || '浏览游记失败');
        }
    }

    // 6. 搜索游记
  static async searchTravelNotes(keyword, PageNum = 1, PageSize = 50) {
    try {
      const response = await apiClient.post(
        '/travel-note/search',
        { PageNum, PageSize },
        {
          params:{ keyword: keyword || '' },
          headers:{
            'content-type': 'multipart/form-data',
          }
        }
      );
      return response.data; // 返回搜索结果
    } catch (error) {
      throw new Error(error.message || '搜索游记失败');
    }
  }

    // 7. 举报游记
    static async reportTravelNote(articleID, reason, token) {
        try {
            const response = await apiClient.post(
                '/travel-note/report',
                { articleID, reason },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        Authorization: `Bearer ${token}`,
                    },
                }
            );
            return response.data; // 返回举报结果
        } catch (error) {
            throw new Error(error.message || '举报游记失败');
        }
    }

    // 8. 关注游记作者
    static async followAuthor(authorID, token) {
        try {
            const response = await apiClient.post(
                '/travel-note/follow-author',
                { authorID },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        Authorization: `Bearer ${token}`,
                    },
                }
            );
            return response.data; // 返回关注结果
        } catch (error) {
            throw new Error(error.message || '关注作者失败');
        }
    }

    // 9. 评论游记
    static async commentOnTravelNote(articleID, comment, parentCommentID = 0, token) {
        try {
            const response = await apiClient.post(
                '/travel-note/comment',
                { articleID, comment, parentCommentID },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        Authorization: `Bearer ${token}`,
                    },
                }
            );
            return response.data; // 返回评论结果
        } catch (error) {
            throw new Error(error.message || '评论游记失败');
        }
    }

    // 10. 收藏游记
    static async collectTravelNote(articleID) {
        try {
            const response = await apiClient.post(
                '/travel-note/collect',
                { articleID },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }
            );
            return response.data; // 返回收藏结果
        } catch (error) {
            throw new Error(error.message || '收藏游记失败');
        }
    }

    // 11. 获取文章第一张图片
    static async getFirstImage(articleID) {
        try {
            const response = await apiClient.get(`/travel-note/firstimage?articleID=${articleID}`, {
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            return response.data; // 返回第一张图片信息
        } catch (error) {
            // 如果是"该文章没有图片"的错误，返回null而不是抛出异常
            if (error.response && error.response.data && error.response.data.includes("该文章没有图片")) {
                return null;
            }
            throw new Error(error.message || '获取文章图片失败');
        }
    }

    // 12. 获取文章所有图片
    static async getArticleImages(articleID) {
        try {
            const response = await apiClient.get(`/travel-note/image?articleID=${articleID}`, {
                headers: {
                    'Content-Type': 'application/json',
                },
            });
            return response.data; // 返回图片列表
        } catch (error) {
            // 如果是"该文章没有图片"的错误，返回空数组而不是抛出异常
            if (error.response && error.response.data && error.response.data.includes("该文章没有图片")) {
                return [];
            }
            throw new Error(error.message || '获取文章图片列表失败');
        }
    }

    // 13. 删除收藏
    static async deleteCollection(favoriteID) {
        try {
            const response = await apiClient.delete(
                `/travel-note/delete?favoriteID=${favoriteID}`,
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }
            );
            return response.data; // 返回删除结果，成功时为字符串"收藏成功"
        } catch (error) {
            throw new Error(error.message || '删除收藏失败');
        }
    }
}
